package org.rency.common.utils.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * Javascript脚本工具类
 * @author: user_rcy@163.com
 * </br>Created on
 * @version: V1.0.0
 * @since JDK 1.8
 */
public class ScriptUtils {

    private static final Logger logger = LoggerFactory.getLogger(ScriptUtils.class);

    /**
     * 执行Javascript脚本
     * </br>Created on 2015年12月15日
     * @param scriptContent 脚本内容
     * @param methodName 函数方法名
     * @return
     * @throws ScriptException
     */
    public static String execScript(String scriptContent,String methodName) throws ScriptException {
        logger.info("执行Script脚本:[{}].",scriptContent);
        String resultData = "";
        try {
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine se = sem.getEngineByName("javascript");
            Invocable invocableEngine = (Invocable) se;
            se.eval(scriptContent);
            resultData = String.valueOf(invocableEngine.invokeFunction(methodName));
            logger.debug("执行Script脚本结果:[{}],脚本内容:[{}].",resultData,scriptContent);
        } catch (ScriptException e) {
            throw e;
        } catch (NoSuchMethodException e) {
        	throw new ScriptException(e);
        }
        logger.info("执行Script脚本完成:[{}].",scriptContent);
        return resultData;
    }

    /**
     * 执行Javascript脚本
     * </br>Created on 2015年12月15日
     * @param scriptContent 脚本内容
     * @param methodName 函数方法名
     * @param params 方法参数
     * @return
     * @throws ScriptException
     */
    public static String execScript(String scriptContent,String methodName,Object... params) throws ScriptException{
        logger.info("执行Script脚本:[{}]-[{}].",scriptContent,params);
        String resultData = "";
        try {
            ScriptEngineManager sem = new ScriptEngineManager();
            ScriptEngine se = sem.getEngineByName("javascript");
            Invocable invocableEngine = (Invocable) se;
            se.eval(scriptContent);
            resultData = String.valueOf(invocableEngine.invokeFunction(methodName,params));
            logger.debug("执行Script脚本结果:[{}],脚本内容:[{}].",resultData,scriptContent);
        } catch (ScriptException e) {
            logger.error("执行Script脚本异常.[{}].",scriptContent,e);
            throw e;
        } catch (NoSuchMethodException e) {
            logger.error("执行Script脚本异常.[{}].",scriptContent,e);
            throw new ScriptException(e);
        }
        logger.info("执行Script脚本完成:[{}].",scriptContent);
        return resultData;
    }

}
